package com.peng.dao.impl;

import com.peng.dao.staffDao;
import com.peng.dao.userDao;
import com.peng.dao.user_typeDao;
import com.peng.entity.staff;
import com.peng.util.BaseDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 欧阳欣鹏 on 2018/8/6.
 */
public class staffDaoImpl implements staffDao
{
    @Override
    public List<staff> li() {
        List<staff> slist=new ArrayList<staff>();
        String sql="select * from staff";
        Connection con=null;
        PreparedStatement st=null;
        ResultSet rs=null;
        try {
            con= BaseDao.getConnection();
            st=con.prepareStatement(sql);
            rs=st.executeQuery();
            while (rs.next()) {
               staff s=new staff();
               s.setStaffid(rs.getInt("staffid"));
               s.setUserid(rs.getInt("userid"));
               s.setAgencyid(rs.getInt("agencyid"));
               user_typeDao dao=new user_typeDaoImpl();
               s.setType(dao.li());
               userDao daoo=new userDaoImpl();
               s.setList(daoo.li(s.getUserid()));
               slist.add(s);

            }
        } catch (Exception e) {
            // TODO: handle exception
        }finally{
            BaseDao.closeConnection(con, st, rs);
        }
        return slist;
    }

    @Override
    public staff li(int id) {
        staff s=null;
        String sql="select * from staff where staffid=?";
        Connection con=null;
        PreparedStatement st=null;
        ResultSet rs=null;
        try {
            con= BaseDao.getConnection();
            st=con.prepareStatement(sql);
            st.setInt(1,id);
            rs=st.executeQuery();
            while (rs.next()) {
                 s=new staff();
                s.setStaffid(rs.getInt("staffid"));
                s.setUserid(rs.getInt("userid"));
                s.setAgencyid(rs.getInt("agencyid"));
                user_typeDao dao=new user_typeDaoImpl();
                s.setType(dao.li());
                userDao daoo=new userDaoImpl();
                s.setList(daoo.li(s.getUserid()));

            }
        } catch (Exception e) {
            // TODO: handle exception
        }finally{
            BaseDao.closeConnection(con, st, rs);
        }
        return s;
    }

    @Override
    public int delete(int id) {
        String sql="DELETE s,u,w from staff as s LEFT JOIN `user` as u on s.userid=u.uid RIGHT JOIN `work` as w on s.staffid=w.staffid WHERE s.staffid=?";
        Object[] ob={id};
        return BaseDao.idu(sql,ob);
    }

    @Override
    public int insert(staff s) {
        try {
            String sql="insert into staff value(null,(SELECT MAX(uid) from `user`),1 )";
//        Object[] ob={s.getAgencyid()};
            return BaseDao.idu(sql,null);
        }catch (Exception e){
            e.printStackTrace();

            return 0;
        }

    }


}
